package com.neusoft.elm.infrastructure.persistence;

import com.neusoft.elm.domain.entity.User;
import com.neusoft.elm.domain.repository.UserRepository;
import com.neusoft.elm.infrastructure.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserRepositoryImpl implements UserRepository {
    private Connection con = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;

    @Override
    public User findByUserIdAndPassword(String userId, String password) {
        User user = null;
        String sql = "select * from user where userId=? and password=?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1, userId);
            pst.setString(2, password);
            rs = pst.executeQuery();
            if (rs.next()) {
                user = new User();
                user.setUserId(rs.getString("userId"));
                user.setPassword(rs.getString("password"));
                user.setUserName(rs.getString("userName"));
                user.setUserSex(rs.getInt("userSex"));
                user.setUserImg(rs.getString("userImg"));
                user.setDelTag(rs.getInt("delTag"));
            }
        } catch (Exception e) {
            throw new RuntimeException("查询用户失败", e);
        } finally {
            DBUtil.close(rs, pst);
        }
        return user;
    }

    @Override
    public int countByUserId(String userId) {
        int result = 0;
        String sql = "select count(*) from user where userId=?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1, userId);
            rs = pst.executeQuery();
            if (rs.next()) {
                result = rs.getInt(1);
            }
        } catch (Exception e) {
            throw new RuntimeException("查询用户数量失败", e);
        } finally {
            DBUtil.close(rs, pst);
        }
        return result;
    }

    @Override
    public int save(User user) {
        int result = 0;
        String sql = "insert into user values(?,?,?,?,?,1)";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1, user.getUserId());
            pst.setString(2, user.getPassword());
            pst.setString(3, user.getUserName());
            pst.setInt(4, user.getUserSex());
            pst.setString(5, user.getUserImg());
            result = pst.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException("保存用户失败", e);
        } finally {
            DBUtil.close(pst);
        }
        return result;
    }
} 